import {
  defaultIfEmpty,
  EMPTY,
  every,
  find,
  findIndex,
  fromEvent,
  interval,
  isEmpty,
  of,
  take,
  takeUntil,
} from "rxjs";

const docEvent = fromEvent(document, "click");

export const defaultEmptyDemo = () => {
  const clickBefore = docEvent.pipe(takeUntil(interval(5000)));

  const lastResult = clickBefore.pipe(defaultIfEmpty("ok it is over")); // 如果是默认没有数据时，这里做默认处理

  lastResult.subscribe((x) => console.log(x)); // 5s 以内没有点击事件后给出默认的 'ok it is over'
};

export const everyDemo = () => {
  of(1, 2, 3, 4, 5, 6)
    .pipe(every((x) => x < 5))
    .subscribe((x) => console.log(x)); // -> false
};

export const findDemo = () => {
  of(1, 2, 3, 4, 5, 6)
    .pipe(find((x) => x < 5))
    .subscribe((x) => console.log(x)); // -> 1, 找到第一个就结束了
};

export const findIndexDemo = () => {
  of(1, 2, 3, 4, 5, 6)
    .pipe(findIndex((x) => x < 5))
    .subscribe((x) => console.log(x)); // -> 0, 找到第一个就结束了
};

export const isEmptyDemo = () => {
  const result = EMPTY.pipe(isEmpty());
  result.subscribe((x) => console.log(x)); // 主要是用来判断当前 obserable 是否为空

  // 创建一个每秒发出一个值的 Observable，并只取前 0 个值
  const source$ = interval(1000).pipe(take(0));

  // 使用 isEmpty 操作符
  const result$ = source$.pipe(isEmpty());

  // 订阅结果 Observable
  result$.subscribe((value) => {
    console.log("Is empty:", value); // true
  });
};
